<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-odometer"></i> 数据分析流水线
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">
      <el-table
          :data="tableData" border class="table" ref="multipleTable"
          header-cell-class-name="table-header"
      >
        <el-table-column prop="pipelineName" label="流水线名"></el-table-column>
        <el-table-column prop="analysisFunction" label="分析方法">
          <template #default="scope">
            {{handleAlgorithmName(scope.row.analysisFunction)}}
          </template>
        </el-table-column>
        <el-table-column prop="chosenColumns" label="选中字段" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="text" @click="handleUsePipeline(scope.row.id)">使用</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                       :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>
    <el-dialog
        v-model="usePipelineVisible"
        title="流水线使用"
        width="30%"
        :before-close="handleClose"
    >
      <el-form :model="useForm" width="300px">
        <el-form-item label="选择文件" >
          <el-select v-model="useForm.file" :label-width="formLabelWidth" placeholder="请选择您要使用的文件">
            <el-option
                v-for="item in fileList.valueOf()"
                :key="item.id"
                :label="item.fileName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="usePipelineVisible = false">取消</el-button>
            <el-button type="primary" @click="goPipeline(useForm.file)" style="margin-left: 10px">使用流水线</el-button>
          </span>
      </template>
    </el-dialog>

    <el-dialog v-model="visualizeVisible" title="可视化" @open="open(chart.analysisFunction)" width="700px">
      <el-form :model="chart" width="400px">
        <el-form-item label="分析函数: " >
          {{chart.analysisFunction}}
        </el-form-item>
        <el-form-item label="分析结果: " v-if="chart.analysisFunction!=='SCATTER_PLOT'">
          {{chart.analysisResult}}
        </el-form-item>
        <el-form-item label="可视化: " v-if="chart.analysisFunction === 'DATA_DISTRIBUTION'">
          <div id="chartPie" style="width: 600px;height: 300px" ></div>
        </el-form-item>
        <el-form-item label="可视化: " v-if="chart.analysisFunction === 'SCATTER_PLOT'">
          <div id="scatter" style="width: 600px;height: 300px" ></div>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {inject, nextTick, reactive, ref} from "vue";
import {deleteAnalysisPipeline, getAllAnalysisPipeline, useAnalysisPipeline} from "../../api/analysisPipeline";
import {ElMessage, ElMessageBox} from "element-plus";
import {GetAllFile} from "../../api/file";

export default {
  name: "AnalysisPipeline",

  setup(){
    const query = reactive({
      file: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const pageTotal = ref(0);
    const tableData = ref();
    let usePipelineVisible = ref(false)
    let useForm = reactive({
      file: "",
    })
    const formLabelWidth='120px'
    const fileList = ref()
    let usePipelineId = ref()
    let visualizeVisible = ref(false)
    const chart = reactive({
      analysisFunction: '',
      analysisResult: {},
      pieResult: {},
    })
    let scatterData = ref([])
    let scatterKey = ref([])

    const echarts = inject('echarts')
    const echartsScatter = inject('echarts')

    const getPage = () => {
      const userId=localStorage.getItem("ms_userId")
      GetAllFile(userId).then(res=>{
        fileList.value=res.result;
      })
      getAllAnalysisPipeline({userId}).then(res =>{
        tableData.value = res.result
        pageTotal.value = tableData.value.length
      })
    }
    getPage()

    const handleUsePipeline = (pid) => {
      usePipelineVisible.value = true
      usePipelineId.value = pid
    }
    const goPipeline = (fileId) => {
      if (fileId === ""){
        alert("请填写信息！")
        return
      }
      usePipelineVisible.value = false
      let data ={
        pipelineId: usePipelineId.value,
        fileId: fileId
      }
      ElMessageBox( {
        title: "确定要使用流水线吗？",
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '分析中...'
            useAnalysisPipeline(data).then(res=>{
              instance.confirmButtonLoading = false
              if (res.msg === '成功')
              {
                done()
                handleVisualize(res.result)
              }
              else
              {
                ElMessage.error("分析失败!:"+res.msg);
                done()
              }
            }).catch(err=>{
              console.log(err)
            });
          } else {
            done()
          }
        },
      })
    }

    const handleDelete = (pipelineId) => {
      ElMessageBox.confirm("确定要删除此流水线吗？", "提示", {
        type: "warning",
      }).then(()=>{
        deleteAnalysisPipeline({pipelineId}).then(res=>{
          if(res.msg === '成功'){
            ElMessage.success("删除成功");
            getPage()
          }
          else{
            ElMessage.error("删除失败:"+res.msg);
          }
        })
      })
    }
    const handleVisualize = (result) => {
      chart.analysisFunction = result.analysisFunction
      if(chart.analysisFunction === 'SCATTER_PLOT'){
        let tempArr= JSON.parse(result.analysisResult)
        let tempObj = tempArr[0]
        let out_arr = []
        for(let key in tempObj){
          out_arr.push(key)
        }
        scatterKey = out_arr
        let tempScatterData = []
        for (let i in tempArr){
          let temp = []
          for (let j in tempArr[i]){
            temp.push(tempArr[i][j])
          }
          tempScatterData.push(temp)
        }
        scatterData = tempScatterData
      }
      else {
        chart.analysisResult = result.analysisResult
      }

      visualizeVisible.value = true

      if(chart.analysisFunction === 'DATA_DISTRIBUTION'){
        let out_arr = []
        let in_obj = JSON.parse(chart.analysisResult)
        for(let key in in_obj){
          let temp = {};			//创建临时对象
          temp.name = key;		//存储对象的Key为name
          temp.value = in_obj[key];	//存储value
          out_arr.push(temp);
        }
        chart.pieResult = out_arr
        console.log(chart.pieResult)
      }

    }
    const drawChart = () => {
      let myChart = echarts.init(document.getElementById("chartPie"));
      myChart.setOption({
        //鼠标悬浮
        tooltip: {
          trigger: "item",
          // formatter: "{a}<br/>{b}: <br/>{c}({d}%)",  其中 {a}指向name名称（访问来源）
          formatter: "{b}: <br/>{c}({d}%)",
        },
        // legend: {
        //   // data: ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"],
        //   right: 300,
        //   orient: "vertical",
        //   // 下面注释的代码是控制分类放在哪个地方,需要体验的话，直接把上面的代码注释，把下面的代码解开注释即可
        //     data: ["红", "黄", "绿"],
        //     // left: "center",
        //     // top: "bottom",
        //     // orient: "horizontal"
        // },
        series: [
          {
            name: "???",
            type: "pie",
            //圆圈的粗细
            radius: ["50%", "80%"],
            //圆圈的位置
            center: ["50%", "50%"],
            data:  chart.pieResult,
            animationDuration: 2000,
            //控制是否显示指向文字的,默认为true
            label: {
              // show: false,
              // position: "center",
              //以下代码可以代表指向小文字的
              show: true,
              formatter: "{b} : {d}%",
              textStyle: {
                color: "#333",
                fontSize: 14,
              },
            },
          },
        ],
      })
      window.onresize = function () {
        myChart.resize()
      }
    }

    const drawScatter = () => {
      let myChart = echartsScatter.init(document.getElementById("scatter"));
      myChart.setOption({
        color: [
          '#dd4444', '#fec42c', '#80F1BE'
        ],
        grid:{
          right: '20%'
        },
        tooltip: {
          //十字线
          axisPointer: {
            type: 'cross'
          },
          padding: 10,
          backgroundColor: '#222',
          borderColor: '#777',
          borderWidth: 1,
          //设置tooltip的显示内容
          formatter: function (obj) {
            let value = obj.value;
            return '<div style="border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">'
                +  '具体数据：'
                + '</div>'
                + scatterKey[0] + '：' + value[0] + '<br>'
                + scatterKey[1] + '：' + value[1] + '<br>'
                + scatterKey[2] + '：' + value[2] + '<br>'
          }
        },
        xAxis: {
          name: scatterKey[0],
          splitLine: {
            show: false
          },
        },
        yAxis: {
          name: scatterKey[1],
          splitLine: {
            show: false
          }
        },
        visualMap: [
          {
            left: 'right',
            top: '10%',
            dimension: 2,
            min: 0,
            max: 20,
            itemWidth: 30,
            itemHeight: 120,
            calculable: false,
            precision: 0.1,
            text: ['个数'],
            textGap: 30,
            inRange: {
              symbolSize: [10, 70]
            },
            outOfRange: {
              symbolSize: [10, 70],
              color: ['rgba(255,255,255,.2)']
            },
            controller: {
              inRange: {
                color: ['#c23531']
              },
              outOfRange: {
                color: ['#444']
              }
            }
          },
        ],
        series: [
          {
            type: 'scatter',
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(120, 36, 50, 0.5)',
              shadowOffsetY: 5,
            },
            data: scatterData,
          }
        ]
      })
      window.onresize = function () {
        myChart.resize()
      }
    }


    const open = (func) =>{
      if (func === 'DATA_DISTRIBUTION'){
        nextTick(() => {
          drawChart()
        })
      }
      else if (func === 'SCATTER_PLOT'){
        nextTick(() => {
          drawScatter()
        })
      }
    }

    const handleAlgorithmName=(name)=>{
      if (name === "DATA_DISTRIBUTION") {
        return "数据分布";
      } else if (name === "SCATTER_PLOT") {
        return "散点图";
      } else if (name === "STATISTICS") {
        return "数据统计";
      } else if (name === "SKEWNESS_KURTOSI") {
        return "偏度-峰度";
      } else if (name === "PEARSON") {
        return "皮尔森相关系数";
      }
    }

    return{
      query,
      pageTotal,
      tableData,
      usePipelineVisible,
      useForm,
      formLabelWidth,
      fileList,
      usePipelineId,
      visualizeVisible,
      chart,
      scatterData,
      scatterKey,
      echarts,
      echartsScatter,
      getPage,
      handleUsePipeline,
      handleDelete,
      goPipeline,
      handleVisualize,
      drawChart,
      drawScatter,
      open,
      handleAlgorithmName
    }
  }

}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.green {
  color: rgb(32, 220, 88)
}
.yellow{
  color:yellowgreen;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
